﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE;
using System.Diagnostics;
using System.Reflection;

namespace VsxFactory.Modeling.VisualStudio
{
#if DEBUG
    public static class DebugComTypeViewer
    {
        private static bool reentrance = false;

        /// <summary>   
        /// Identifies the internal object types.   
        /// </summary>   
        /// <param name="item">The item.</param>          
        public static void IdentifyInternalObjectTypes(object item)
        {
            if (item == null)
            {
                Debug.WriteLine("No item object is available.");
                return;
            }

            // Loop through all the assemblies in the current app domain   
            Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();

            // Loop through each assembly   
            for (Int32 index = 0; index < loadedAssemblies.Length; index++)
            {
                // Assume that the assembly to check against is EnvDTE.dll   
                IdentifyInternalObjectTypes(item, loadedAssemblies[index]);
            }
        }

        /// <summary>   
        /// Identifies the internal object types.   
        /// </summary>   
        /// <param name="item">The item.</param>   
        /// <param name="assemblyToCheck">The assembly to check.</param>   
        private static void IdentifyInternalObjectTypes(object item, Assembly assemblyToCheck)
        {
            if (reentrance)
                return;
            reentrance = true;
            try
            {
                // Get the types that are publically available   
                Type[] exportedTypes = assemblyToCheck.GetExportedTypes();

                // Loop through each type   
                for (Int32 index = 0; index < exportedTypes.Length; index++)
                {
                    // Check if the object instance is of this type   
                    if (exportedTypes[index].IsInstanceOfType(item))
                    {
                        Debug.WriteLine(exportedTypes[index].FullName);
                    }
                }
            }
            catch
            {
                Debug.WriteLine(String.Format("Unable to get exported types from assembly {0}", assemblyToCheck.FullName));
            }
            finally
            {
                reentrance = false;
            }
        }
    }
#endif
}